﻿using System;

namespace TK
{
    public partial class CustomSerializer
    {
        void writeEnum(CustomSerializerState state, object value)
        {
            var typeAttrs = getTypeAttributes(value.GetType());
            Attribute aValue;
            if (typeAttrs.TryGetValue(typeof (CSOption), out aValue) && ((CSOption) aValue).As == StoreAs.Name) {
                var values = value.ToString();
                SimpleTypes[typeof (string)].Write(state, values);
            }
            else {
                var underType = value.GetType().GetEnumUnderlyingType();
                SimpleTypes[underType].Write(state, Convert.ChangeType(value, underType));
            }
        }

        object readEnum(CustomSerializerState state, Type storedType, Type expectedType) {
            var typeAttrs = getTypeAttributes(expectedType);
            Attribute aValue;
            if (typeAttrs.TryGetValue(typeof (CSOption), out aValue) && ((CSOption) aValue).As == StoreAs.Name) {
                var values = SimpleTypes[typeof (string)].Read(state) as string;
                if (string.IsNullOrEmpty(values)) return getDefaultValue(expectedType);
                try { Enum.Parse(expectedType, values); }
                catch {
                    return getDefaultValue(storedType); // todo
                }
            }
            
            var simpleValue = SimpleTypes[storedType.GetEnumUnderlyingType()].Read(state);
            return Enum.ToObject(expectedType, simpleValue);
        }
    }
}